package com.example.pokemon_chat_room.request;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.json.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttp {

    public static final String ACTION_EXPIRED_MESSAGE = "com.example.pokemon_chat_room.EXPIRED";
    public static final String KEY_RECEIVED_DATA = "error";
    String ip = "http://1.15.138.41:9091/";
    String response = null;

    private Context mContext;

    public JSONObject Post(Context context ,String url, JSONObject json) throws IOException {
        mContext = context;
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");

        RequestBody formBody = RequestBody.create(JSON, String.valueOf(json));
        Request request = new Request.Builder().url(ip + url)
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        response = Objects.requireNonNull(call.execute().body()).string();
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getString("message").equals("EXPIRED")) {
            sendMessageBroadcast("登录状态过期");
        }
        return jsonObject;
    }

    private void sendMessageBroadcast(String message){
        if (!message.isEmpty()){
            Intent intent = new Intent();
            intent.setAction(ACTION_EXPIRED_MESSAGE);
            intent.putExtra(KEY_RECEIVED_DATA, message);

            showLog("发送收到的消息");
            mContext.sendBroadcast(intent);
        }
    }
    private void showLog(String msg){
        Log.d("WebClient---->", msg);
    }
}
